//
//  ScanLoginVC.m
//  SchoolHelper
//
//  Created by  任辰东 on 2020/4/7.
//  Copyright © 2020 JSY. All rights reserved.
//

#define LBXScan_Define_Native  //下载了native模块
#define LBXScan_Define_UI     //下载了界面模块

#import "ScanLoginVC.h"
#import <LBXScanViewController.h>
#import <LBXScanView.h>
#import "UIButton+TouchAreaInsets.h"
#import "RCDAlertView.h"
#import "ScanLoginConfirmVC.h"
#import "HomePageApis.h"
#import "ScanModel.h"

@interface ScanLoginVC ()<LBXScanViewControllerDelegate>
@property (nonatomic,weak) LBXScanViewController *scanVc;///<<#name#>
@property (nonatomic,weak) UIButton *btnFlash;///<<#name#>
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) UILabel *tipsLabel;
@end

@implementation ScanLoginVC

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationItem setTitle:@"扫描二维码"];
    self.view.backgroundColor = UIColorFromHex(0x000000);
    
    LBXScanViewController *scanVc = [LBXScanViewController new];
    scanVc.delegate = self;
    scanVc.libraryType = SLT_Native;
    scanVc.scanCodeType = SCT_QRCode;
    scanVc.style = [self customStyle];
    [self addChildViewController:scanVc];
    [self.view addSubview:scanVc.view];
    [scanVc.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    self.scanVc = scanVc;
    
    UIButton *btnFlash = [UIButton buttonWithType:UIButtonTypeCustom];
    btnFlash.titleLabel.font = UIFontSize(16);
    [btnFlash setTitle:@"轻触点亮" forState:UIControlStateNormal];
    [btnFlash setTitleColor:UIColorFromHex(0xffffff) forState:UIControlStateNormal];
    btnFlash.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
    [btnFlash addTarget:self action:@selector(openOrCloseFlash) forControlEvents:UIControlEventTouchUpInside];
    [scanVc.view addSubview:btnFlash];
    [scanVc.view bringSubviewToFront:btnFlash];
    [btnFlash mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.equalTo(self.view.mas_centerY).offset((kScreenWidth-120)/2 -40);
        
    }];
    self.btnFlash = btnFlash;
    
    [self.view addSubview:self.backBtn];
    [self.backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).offset(20);
        make.top.equalTo(self.view).offset(KStatusBarHeight+20);
        make.height.width.mas_equalTo(25);
    }];
    
    [self.view addSubview:self.tipsLabel];
    [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_centerY).offset((kScreenWidth-120)/2 +10);
    }];
    
}

-(void)backBtnAction
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

//开关闪光灯
- (void)openOrCloseFlash
{
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    
    [self.scanVc openOrCloseFlash];
    
    if (self.scanVc.isOpenFlash)
    {
        [self.btnFlash setTitle:@"轻触关闭" forState:UIControlStateNormal];
    }
    else
        [self.btnFlash setTitle:@"轻触点亮" forState:UIControlStateNormal];
}

- (LBXScanViewStyle* )customStyle{
    //设置扫码区域参数设置
    
    //创建参数对象
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    
    //矩形区域中心上移，默认中心点为屏幕中心点
    style.centerUpOffset = 44;
    
    //扫码框周围4个角的类型,设置为外挂式
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_On;
    
    //扫码框周围4个角绘制的线条宽度
    style.photoframeLineW = 2;
    
    //扫码框周围4个角的宽度
    style.photoframeAngleW = 24;
    
    //扫码框周围4个角的高度
    style.photoframeAngleH = 24;
    
    //四个角颜色
    style.colorAngle = [UIColor whiteColor];
    
    //边框颜色
    style.colorRetangleLine = [UIColor colorWithRed:150/255. green:150/255. blue:150/255. alpha:1.0];
    
    //扫码框内 动画类型 --线条上下移动
    style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
    
    //线条上下移动图片
    style.animationImage = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_light_green"];
    
    style.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    
    
    return style;
}

#pragma mark- LBXScanViewControllerDelegate
- (void)scanResultWithArray:(NSArray<LBXScanResult *> *)array{
    if (array.count < 1)
    {
        return;
    }
    
    //经测试，可以同时识别2个二维码，不能同时识别二维码和条形码
    for (LBXScanResult *result in array) {
        
        NSLog(@"scanResult:%@",result.strScanned);
    }
    
    LBXScanResult *scanResult = array[0];
    
    NSString*strResult = scanResult.strScanned;
    
    
    if (!strResult) {
        
        return;
    }
    
    AudioServicesPlaySystemSound(1057);
    
    [self requestCheckQRWithId:strResult];
    
    //    UIAlertController *alVC = [UIAlertController alertControllerWithTitle:strResult message:nil preferredStyle:UIAlertControllerStyleAlert];
    //    [alVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //        [self.scanVc reStartDevice];
    //    }]];
    //    [self presentViewController:alVC animated:YES completion:nil];
    
}

- (void)requestCheckQRWithId:(NSString *)idString
{
//    if (self.scanResultBlock) {
//
//        self.scanResultBlock(idString);
//    }
//    [self.navigationController popViewControllerAnimated:YES];
    
    [self.scanVc stopScan];
    
    if ([idString hasPrefix:@"http"]) {
        
        if (self.scanResultBlock) {
            self.scanResultBlock(idString);
        }
        [self dismissViewControllerAnimated:YES completion:NULL];
        
    } else {
        //    code_no 是唯一码 type 1 学校 2机关 3学生 4家长

            NSDictionary *dic = (NSDictionary *)[idString mj_JSONObject];
            ScanModel *model = [ScanModel mj_objectWithKeyValues:dic];
//            NSNumber *type = dic[@"type"];
//            NSString *code_no = dic[@"code_no"];
            
            if (model.type.integerValue == 3) {
                
                [self codeSuccessRequest:model.code_no];
            }else{
                RCDAlertView *alertView = [[RCDAlertView alloc]initWithTile:@"提示" subTitle:@"你扫描的二维码不是教之源错题本工作台\n登录码,请核实后重新扫码" cancelTitle:@"" confirmTitle:@"取消"];
                [alertView show];
                WeakSelf
                [alertView setDidConfirm:^{
                   StrongSelf
                    [self.scanVc reStartDevice];
                }];
            }
    }
}

- (void)codeSuccessRequest:(NSString *)code_no
{
    WeakSelf
    [self showLoadingHUDWithMessage:@"扫描成功"];
    [HomePageApis codeSuccessRequestWithCode_no:code_no SuccessBlock:^(NSNumber *code, NSString *msg, id responseData) {
        StrongSelf
        [self hideLoadingHUD];
        ScanLoginConfirmVC *confirmVC = [[ScanLoginConfirmVC alloc]initWithCode_no:code_no];
        [self.navigationController pushViewController:confirmVC animated:YES];
    } FailureBlock:^(NSNumber *code, NSString *msg) {
        StrongSelf
        [self showWarningHUDWithMessage:msg completion:NULL];
    }];
}

#pragma mark -- lazylaod

-(UIButton *)backBtn
{
    if (!_backBtn) {
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backBtn setImage:UIImageWithName(@"close") forState:UIControlStateNormal];
        [_backBtn setTouchAreaInsets:UIEdgeInsetsMake(20, 20, 20, 20)];
    }
    return _backBtn;
}

-(UILabel *)tipsLabel
{
    if (!_tipsLabel) {
        _tipsLabel = [UILabel new];
        _tipsLabel.text = @"扫二维码";
        _tipsLabel.textColor = UIColorFromHex(0xffffff);
        _tipsLabel.font = UIFontSize(15);
        _tipsLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipsLabel;
}

@end
